#region Page Code

#region Author Info
/*
###############################################################################################
#                                                                                             # 
# The page is used to manage insurance names.                                                 #
# The data will be used from the tbl_InsuranceCompanies table                                 #
#     Author : Kajal Mandal                                                                   #
#     Dated  : 11-Oct-2006                                                                    #
#                                                                                             #
###############################################################################################
*/

#endregion

#region Namespace
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using SiteManager;
#endregion

#region Class
public partial class Admin_Ad_ManageInsurance : System.Web.UI.Page
{

    #region Var
    //Create an Object of Manager which is defined in the namespace SiteManager
    Manager mgr = new Manager(true,"ConnectionString");
    //Common DataSet
    DataSet ds;
    public int id = 0;
    public string path = "";
    #endregion

    #region Page Load
    protected void Page_Load(object sender, EventArgs e)
    {
        //This unload event handler will close all the used global instances
        Page.Unload += new EventHandler(Page_Unload);
        lblMsg.Text = "";
        if (!IsPostBack)
        {
            //Bind the grid for the first time
            BindTheGrid();
        }
        return;
    }

    #endregion

    #region BindGrid

    /// <summary>
    /// This is the common function used to bind the GridView "InsuranceGrid"
    /// </summary>
    /// <remarks>
    /// AUTHOR: Kajal Mandal
    /// DATE:   11 October 2006
    /// </remarks>
    void BindTheGrid()
    {
        if (ViewState["Search"] != null)
        {
            if (ViewState["Search"].ToString() == "True")
            {
                SqlParameter[] sp = new SqlParameter[1];
                sp[0] = new SqlParameter("@CRITERIA", SqlDbType.VarChar, 200);
                sp[0].Value = "%" + txtSearch.Text + "%";
                ///Stored procedure [spSearchInusranceCompanies] returns all 
                ///the data from the table 'tbl_insurancecompanies' as per criteria.
                ds = mgr.ExecuteQuery("spSearchInusranceCompanies", sp, "tbl");
            }
            else
            {
                ///Stored procedure [spAllInusranceCompanies] returns all 
                ///the data from the table 'tbl_insurancecompanies'.
                ds = mgr.ExecuteQuery("spAllInusranceCompanies", "tbl");
            }
        }
        else
        {
            ds = mgr.ExecuteQuery("spAllInusranceCompanies", "tbl");
        }
        InsuranceGrid.DataSource = ds;
        InsuranceGrid.DataBind();

        foreach (GridViewRow gvr in InsuranceGrid.Rows)
        {
            foreach (Control ctl in gvr.Cells[2].Controls)
            {
                if (ctl.GetType().ToString().IndexOf("DataControlImageButton") > 0)
                {
                    ImageButton lnk = (ImageButton)ctl;
                    if (lnk.AlternateText.ToUpper() == "DELETE")
                    {                        
                        lnk.Attributes.Remove("onclick");
                        lnk.Attributes.Add("onclick", 
                            "if(confirm('Are you sure want to delete this record?')){__doPostBack('InsuranceGrid','" + lnk.ClientID + "');}else{return false}");
                    }
                }
            }
        }
    }

    #endregion

    #region Unload
    /// <summary>
    /// Unload all the globally-used instances to free all the allocated memory
    /// </summary>
    /// <remarks>
    /// AUTHOR: Kajal Mandal
    /// DATE:   11 October 2006
    /// </remarks>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    void Page_Unload(object sender, EventArgs e)
    {
        ds = null;
        mgr = null;
        return;
    }
    #endregion

    #region Edit Paging
    /// <summary>
    /// This function is called when the user tries to change the GridView Page
    /// </summary>
    /// <remarks>
    /// AUTHOR: Kajal Mandal
    /// DATE:   11 October 2006
    /// </remarks>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void InsuranceGrid_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        InsuranceGrid.PageIndex = e.NewPageIndex;
        InsuranceGrid.EditIndex = -1;
        BindTheGrid();
    }

    /// <summary>
    /// This function will catch the "Edit" event of the GridView control
    /// </summary>
    /// <remarks>
    /// AUTHOR: Kajal Mandal
    /// DATE:   11 October 2006
    /// </remarks>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void InsuranceGrid_RowEditing(object sender, GridViewEditEventArgs e)
    {
        lblMsg.Text = "";
        InsuranceGrid.EditIndex = e.NewEditIndex;
        BindTheGrid();
    }

    /// <summary>
    /// This function will catch the "Cancel" event after Edit Operation of the GridView control
    /// </summary>
    /// <remarks>
    /// AUTHOR: Kajal Mandal
    /// DATE:   11 October 2006
    /// </remarks>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void InsuranceGrid_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        InsuranceGrid.EditIndex = -1;
        BindTheGrid();
    }
    #endregion

    #region UPDATE
    /// <summary>
    /// This function will catch the "Update" event after Edit Operation of the GridView control
    /// </summary>
    /// <remarks>
    /// AUTHOR: Kajal Mandal
    /// DATE:   11 October 2006
    /// </remarks>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void InsuranceGrid_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        try
        {
            ///Extract the data from editted field.
            DataControlFieldCell cell = (DataControlFieldCell)InsuranceGrid.Rows[e.RowIndex].Cells[1];
            InsuranceGrid.Columns[1].ExtractValuesFromCell(e.Keys, cell, DataControlRowState.Edit, true);
            string strNewValue = e.Keys["name"].ToString();
            int id2Update = Convert.ToInt32(InsuranceGrid.Rows[e.RowIndex].Cells[0].Text);

            SqlParameter[] sp = new SqlParameter[3];
            sp[0] = new SqlParameter("@ID", SqlDbType.Int);
            sp[1] = new SqlParameter("@INS_NAME", SqlDbType.VarChar, 200);
            sp[2] = new SqlParameter("@SUCCESS", SqlDbType.Bit);
            sp[0].Value = id2Update;
            sp[1].Value = strNewValue;
            sp[2].Direction = ParameterDirection.Output;

            ///Stored procedure [spUpdateInsurance] updates the table 'tbl_insurancecompanies'.
            ///The insurance id, which is to be updated and the new insurance name is sent through parameter.
            mgr.ExecuteUpdate("spUpdateInsurance", sp);            
            if (Convert.ToBoolean(sp[2].Value))
            {
                lblMsg.ForeColor = System.Drawing.Color.Green;
                lblMsg.Text = "Record updated successfully.";
                InsuranceGrid.EditIndex = -1;
                BindTheGrid();
            }
            else
            {
                lblMsg.ForeColor = System.Drawing.Color.Red;
                lblMsg.Text = "Insurance name already exists!";
            }
        }
        catch (Exception ex)
        {
            lblMsg.ForeColor = System.Drawing.Color.Red;
            lblMsg.Text = "Record UPDATING FAILED! <br/>" + ex.ToString();
        }
        return;
    }

    #endregion

    #region Delete
    /// <summary>
    /// This function will catch the "Delete" event of the GridView control
    /// </summary>
    /// <remarks>
    /// AUTHOR: Kajal Mandal
    /// DATE:   11 October 2006
    /// </remarks>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void InsuranceGrid_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        try
        {
            int id2Delete = Convert.ToInt32(InsuranceGrid.Rows[e.RowIndex].Cells[0].Text);

            SqlParameter[] sp = new SqlParameter[1];
            sp[0] = new SqlParameter("@INSURANCE_ID", SqlDbType.Int);
            sp[0].Value = id2Delete;

            ///Stored procedure [spGetDoctors_Insurance] returns all records from the table 'tbl_Doctor_Insurance',
            ///as per the insurance id sent through parameter.
            SqlDataReader dr = mgr.ExecuteQuery("spGetDoctors_Insurance", sp);

            //If even a single record is found, that means the insurance record is used in some doctor's record.
            //Hence should not be deleted.
            if (dr.Read())
            {
                lblMsg.ForeColor = System.Drawing.Color.Red;
                lblMsg.Text = "Deletion failed. This Insurance Record is associated with a Doctor.";
            }
            else
            {
                try
                {
                    SqlParameter[] sp4Delete = new SqlParameter[1];
                    sp4Delete[0] = new SqlParameter("@INSURANCE_ID", SqlDbType.Int);
                    sp4Delete[0].Value = id2Delete;

                    ///Stored procedure [spDeleteInsurance] deletes a particular record from 
                    ///the table 'tbl_insurancecompanies'. The insurance id is sent through parameter.
                    mgr.ExecuteQuery("spDeleteInsurance", sp4Delete);
                    lblMsg.ForeColor = System.Drawing.Color.Green;
                    lblMsg.Text = "Record deleted successfully.";
                    BindTheGrid();
                }
                catch (Exception ex)
                {
                    Response.Write(ex.ToString());
                    lblMsg.ForeColor = System.Drawing.Color.Red;
                    lblMsg.Text = "Record DELETION FAILED!<br/>" + ex.ToString();
                }
            }
            dr.Close();
        }
        catch (Exception ex)
        {
            Response.Write(ex.ToString());
            lblMsg.ForeColor = System.Drawing.Color.Red;
            lblMsg.Text = "Record UPDATING FAILED! <br/>" + ex.ToString();
        }
        return;
    }


    #endregion

    #region Add Insurance

    /// <summary>
    /// This function will add a newly fed insurance name in the database.
    /// </summary>
    /// <remarks>
    /// AUTHOR: Kajal Mandal
    /// DATE:   11 October 2006
    /// </remarks>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (txtInsuranceName.Text.Trim().Length > 0)
        {
            try
            {
                SqlParameter[] sp = new SqlParameter[2];
                sp[0] = new SqlParameter("@INSURANCE_NAME", SqlDbType.VarChar, 200);
                sp[0].Value = txtInsuranceName.Text.Trim();

                sp[1] = new SqlParameter("@SUCCESS", SqlDbType.Bit);
                sp[1].Direction = ParameterDirection.Output;

                ///Stored procedure [spAddAInsurance] adds a record to the table 'tbl_insurancecompanies'. 
                ///The insurance id is sent through parameter.
                mgr.ExecuteUpdate("spAddAInsurance", sp);
                bool boolSuccess = Convert.ToBoolean(sp[1].Value);
                if (boolSuccess)
                {
                    lblMsg.ForeColor = System.Drawing.Color.Green;
                    lblMsg.Text = "Insurance record added successfully.";
                    BindTheGrid();
                }
                else
                {
                    lblMsg.ForeColor = System.Drawing.Color.Red;
                    lblMsg.Text = "Insurance name already exists.";
                }
                
            }
            catch (Exception ex)
            {
                lblMsg.ForeColor = System.Drawing.Color.Red;
                lblMsg.Text = "Inusrance ADDING FAILED!<br>" + ex.ToString();
            }
        }
    }
    #endregion

    #region Search Btn

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        if (txtSearch.Text.Trim().Length > 0)
        {
            ViewState["Search"] = "True";
            BindTheGrid();
        }
        else
        {
            ViewState["Search"] = null;
            BindTheGrid();
        }
    }
    #endregion

}
#endregion

#endregion